package com.enation.app.javashop.core.promotion.coupon.service.impl;

import com.enation.app.javashop.core.promotion.PromotionErrorCode;
import com.enation.app.javashop.core.promotion.coupon.model.dos.CouponDO;
import com.enation.app.javashop.core.promotion.coupon.service.CouponManager;
import com.enation.app.javashop.framework.context.UserContext;
import com.enation.app.javashop.framework.database.DaoSupport;
import com.enation.app.javashop.framework.database.Page;
import com.enation.app.javashop.framework.exception.NoPermissionException;
import com.enation.app.javashop.framework.exception.ServiceException;
import com.enation.app.javashop.framework.security.model.Seller;
import com.enation.app.javashop.framework.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


/**
 * 优惠券业务类
 * @author Snow
 * @version v2.0
 * @since v7.0.0
 * 2018-04-17 23:19:39
 */
@Service
public class CouponManagerImpl implements CouponManager {

	@Autowired
	@Qualifier("tradeDaoSupport")
	private DaoSupport daoSupport;

	@Override
	public Page list(int page,int pageSize,Long startTime,Long endTime){

		Seller seller = UserContext.getSeller();
		List params = new ArrayList();

		StringBuffer sql = new StringBuffer("select * from es_coupon where seller_id = ? ");
		params.add(seller.getSellerId());

		if(startTime!=null){
			sql.append(" and start_time<=? ");
			params.add(startTime);
		}

		if(endTime!=null){
			sql.append(" and end_time>=? ");
			params.add(endTime);
		}

		sql.append(" order by coupon_id desc");
		Page  webPage = this.daoSupport.queryForPage(sql.toString(),page, pageSize ,CouponDO.class,params.toArray() );

		return webPage;
	}

	@Override
	public List<CouponDO> getList(Integer sellerId) {
		String sql = "select * from es_coupon where seller_id = ? and start_time < ? and end_time > ?";
		List<CouponDO> couponDOList = this.daoSupport.queryForList(sql,CouponDO.class,sellerId,DateUtil.getDateline(),DateUtil.getDateline());
 		return couponDOList;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED,rollbackFor = {ServiceException.class,RuntimeException.class,Exception.class})
	public	CouponDO  add(CouponDO	coupon)	{

		this.daoSupport.insert(coupon);
		int id = this.daoSupport.getLastId("es_coupon");
		coupon.setCouponId(id);

		return coupon;
	}

	@Override
	public	CouponDO  edit(CouponDO	coupon,Integer id){
		this.verifyStatus(id);
		this.daoSupport.update(coupon,id);
		return coupon;
	}

	@Override
	public	void delete( Integer id)	{

		this.verifyStatus(id);
		this.daoSupport.delete(CouponDO.class,id);
	}

	@Override
	public	CouponDO getModel(Integer id)	{

		CouponDO couponDO = this.daoSupport.queryForObject(CouponDO.class,id);

		return couponDO;
	}

	@Override
	public void verifyAuth(Integer id) {
		CouponDO  couponDO =  this.getModel(id);
		if(couponDO == null || !couponDO.getSellerId().equals(UserContext.getSeller().getSellerId())){
			throw new NoPermissionException("无权操作或者数据不存在");
		}
	}

	@Override
	@Transactional(value = "tradeTransactionManager",propagation = Propagation.REQUIRED,rollbackFor = {Exception.class})
	public void addUsedNum(Integer couponId) {
		String sql = "update es_coupon set used_num = used_num+1 where coupon_id=?";
		this.daoSupport.execute(sql,couponId);
	}


	@Override
	@Transactional(value = "tradeTransactionManager",propagation = Propagation.REQUIRED,rollbackFor = {Exception.class})
	public void addReceivedNum(Integer couponId) {
		String sql = "update es_coupon set received_num = received_num+1 where coupon_id=?";
		this.daoSupport.execute(sql,couponId);
	}

	@Override
	public Page all(int page, int pageSize,Integer sellerId) {
		Long nowTime = DateUtil.getDateline();
		List params = new ArrayList();

		StringBuffer sql = new StringBuffer("select * from es_coupon where ? >= start_time and ? < end_time");
		params.add(nowTime);
		params.add(nowTime);

		if(sellerId != null){
			sql.append(" and seller_id = ? ");
			params.add(sellerId);
		}

		sql.append(" order by coupon_id desc");
		Page  webPage = this.daoSupport.queryForPage(sql.toString(),page, pageSize ,CouponDO.class,params.toArray() );

		return webPage;
	}


	/**
	 * 验证是否可修改和删除
	 * @param id
	 */
	private void verifyStatus(Integer id){
		CouponDO couponDO = this.getModel(id);
		long nowTime = DateUtil.getDateline();

		//如果当前时间大于起始时间，小于终止时间，标识活动已经开始了，不可修改和删除。
		if(couponDO.getStartTime().longValue() < nowTime && couponDO.getEndTime().longValue() > nowTime){
			throw new ServiceException(PromotionErrorCode.E400.code(),"活动已经开始，不能进行编辑删除操作");
		}


	}

}
